<template>
  <div class="self-service-registration">
    <!-- 步骤内容 -->
    <div class="step-content">
      <!-- 步骤1: 科室选择 -->
      <DepartmentSelection
        v-if="currentStep === 'department'"
        @department-selected="onDepartmentSelected"
      />

      <!-- 步骤2: 医生选择 -->
      <DoctorSelection
        v-else-if="currentStep === 'doctor'"
        :department-id="selectedDepartment.id"
        :department-name="selectedDepartment.name"
        @doctor-selected="onDoctorSelected"
        @back="goToStep('department')"
      />

      <!-- 步骤3: 支付方式选择 -->
      <PaymentMethodSelection
        v-else-if="currentStep === 'payment-method'"
        :appointment-info="appointmentInfo"
        :department-id="selectedDepartment.id"
        @payment-method-selected="onPaymentMethodSelected"
        @back="goToStep('doctor')"
      />

      <!-- 步骤4: 费用详情 -->
      <FeeDetails
        v-else-if="currentStep === 'fee-details'"
        :appointment-info="appointmentInfo"
        :payment-mode="paymentMode"
        :use-insurance="useInsurance"
        @confirm-payment="onConfirmPayment"
        @back="goToStep('payment-method')"
      />

      <!-- 步骤5: 支付 -->
      <PaymentView
        v-else-if="currentStep === 'payment'"
        :appointment-info="appointmentInfo"
        :payment-mode="paymentMode"
        :use-insurance="useInsurance"
        :payment-data="currentPaymentData" 
        @payment-success="onPaymentSuccess"
        @payment-failed="onPaymentFailed"
        @back="goToStep('fee-details')"
      />

      <!-- 步骤6: 支付结果 -->
      <PaymentResult
        v-else-if="currentStep === 'payment-result'"
        :result-type="paymentResult.type"
        :appointment-info="appointmentInfo"
        :payment-info="paymentResult.info"
        @retry="goHome"
        @home="goHome"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { Check } from "@element-plus/icons-vue";
// 在 setup 函数中添加患者信息检查
import { ElMessage } from "element-plus";

// 子组件
import DepartmentSelection from "./componentsRegistration/DepartmentSelection.vue";
import DoctorSelection from "./componentsRegistration/DoctorSelection.vue";
import PaymentMethodSelection from "./componentsRegistration/PaymentMethodSelection.vue";
import FeeDetails from "./componentsRegistration/FeeDetails.vue";
import PaymentView from "./componentsRegistration/PaymentView.vue";
import PaymentResult from "./componentsRegistration/PaymentResult.vue";

const router = useRouter();

// 获取当前挂号患者的信息
const patientInfo = ref({});

//加载患者信息
const loadPatientInfo = () => {
  patientInfo.value = JSON.parse(localStorage.getItem("currentPatient"));
  console.log("当前患者信息:", patientInfo.value);
};

// 检查患者信息
const checkPatientInfo = () => {
  loadPatientInfo();

  if (!patientInfo.value || Object.keys(patientInfo.value).length === 0) {
    ElMessage.error("请先扫描医保卡获取患者信息");
    return false;
  }
  return true;
};

// 步骤定义
const steps = ref([
  { id: "department", label: "选择科室" },
  { id: "doctor", label: "选择医生" },
  { id: "payment-method", label: "支付方式" },
  { id: "fee-details", label: "费用详情" },
  { id: "payment", label: "确认支付" },
]);

// 当前步骤
const currentStep = ref("department");

// 选中的科室
const selectedDepartment = ref({
  id: null,
  name: "",
});

// 选中的医生
const selectedDoctor = ref({
  id: null,
  name: "",
  title: "",
});

// 支付方式
const paymentMode = ref("insurance"); // insurance医保 | self自费
const useInsurance = ref(false); // 是否使用医保
// 在现有的响应式变量后面添加
const currentPaymentData = ref({}); // 存储完整的支付数据
const insuranceDeduction = ref(0); // 存储医保报销金额

// 挂号信息
const appointmentInfo = ref({
  department_id: "",
  department_name: "",
  doctor_id: "",
  doctor: "",
  fee: 1.0,
  time: "",
  room: "诊室待分配",
});

// 在 SelfServiceRegistration.vue 中添加
const generateAppointmentId = () => {
  const now = new Date();
  const year = now.getFullYear().toString();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  const dateStr = year + month + day;
  const randomNum = Math.floor(100000 + Math.random() * 900000).toString();
  
  return `TJ${dateStr}${randomNum}`;
};

// 支付结果
const paymentResult = ref({
  type: "success", // success | failed
  info: {},
});

// 获取步骤索引
const getStepIndex = (stepId) => {
  return steps.value.findIndex((step) => step.id === stepId);
};

// 跳转到指定步骤
const goToStep = (stepId) => {
  if (getStepIndex(stepId) <= getStepIndex(currentStep.value) + 1) {
    currentStep.value = stepId;
  }
};

// 科室选择事件
const onDepartmentSelected = (department) => {
  if (!checkPatientInfo()) return; // 在这里检查

  selectedDepartment.value = department;
  appointmentInfo.value.department_id = department.id;
  appointmentInfo.value.department_name = department.name;

  goToStep("doctor");
};

// 医生选择事件
const onDoctorSelected = (doctor) => {
  selectedDoctor.value = doctor;
  

  appointmentInfo.value.doctor = `${doctor.name}`;
  appointmentInfo.value.doctor_id = doctor.id; // 添加医生ID
  appointmentInfo.value.department_id = selectedDepartment.value.id; // 确保科室ID存在
  appointmentInfo.value.fee = doctor.fee; // 使用医生的实际费用
  appointmentInfo.value.room = doctor.location; // 使用API返回的诊室位置
  appointmentInfo.value.schedule_instance_id = doctor.schedule_instance_id; // 新增：保存排班实例ID

  // 生成就诊时间（模拟）
  const now = new Date();
  const appointmentDate = new Date(now.getTime() + 24 * 60 * 60 * 1000); // 明天
  const hours = 9 + Math.floor(Math.random() * 8); // 9点-17点之间
  appointmentInfo.value.time = `${appointmentDate.toLocaleDateString()} ${hours}:00`;

  goToStep("payment-method");
};

// 修改费用详情确认支付事件
const onConfirmPayment = (paymentInfo) => {
  // 使用统一的挂号编号，确保与支付数据一致
  const appointmentId = paymentInfo.paymentData?.appointmentId || generateAppointmentId();

  // 保存到 appointmentInfo 中
  appointmentInfo.value.appointmentId = appointmentId;

  // 保存支付数据
  if (paymentInfo.paymentData) {
    currentPaymentData.value = {
      ...paymentInfo.paymentData,
      appointmentId: appointmentId // 统一编号
    };
  }

  goToStep('payment');
};

// 支付方式选择事件
const onPaymentMethodSelected = (method) => {
  paymentMode.value = method.paymentMode;
  useInsurance.value = method.useInsurance;  
  goToStep("fee-details");
};

// 支付成功事件
const onPaymentSuccess = (paymentInfo) => {
  paymentResult.value = {
    type: "success",
    info: paymentInfo,
  };

  // 将挂号编号保存到 appointmentInfo 中，用于后续显示
  if (paymentInfo.appointmentId) {
    appointmentInfo.value.appointmentId = paymentInfo.appointmentId;
  }

  // 将统一的挂号编号保存到 appointmentInfo 中
  appointmentInfo.value.appointmentId = currentPaymentData.value.appointmentId;

  // 传递医保报销金额到 appointmentInfo
  appointmentInfo.value.insuranceDeduction = paymentInfo.insuranceDeduction || insuranceDeduction.value;

  goToStep("payment-result");
};

// 支付失败事件
const onPaymentFailed = (errorInfo) => {
  paymentResult.value = {
    type: "failed",
    info: errorInfo,
  };
  goToStep("payment-result");
};

// 返回首页
const goHome = () => {
  router.push("/self-service");
};

onMounted(() => { 

  // 验证患者信息
  if (!checkPatientInfo()) {
    // 如果患者信息无效，直接返回，不显示任何内容
    router.push("/self-service");
  }  
});
</script>

<style lang="scss" scoped>
.self-service-registration {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.step-progress {
  margin-bottom: 40px;
  padding: 20px 0;

  .step-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;

    &::before {
      content: "";
      position: absolute;
      top: 20px;
      left: 0;
      right: 0;
      height: 2px;
      background: #e4e7ed;
      z-index: 1;
    }
  }

  .step-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    z-index: 2;
    cursor: pointer;
    transition: all 0.3s;

    &.active {
      .step-circle {
        background: #409eff;
        border-color: #409eff;
        color: white;
      }

      .step-label {
        color: #409eff;
        font-weight: 600;
      }
    }

    &.completed {
      .step-circle {
        background: #67c23a;
        border-color: #67c23a;
        color: white;
      }

      .step-label {
        color: #67c23a;
      }
    }

    &:not(.active):not(.completed):hover {
      .step-circle {
        border-color: #409eff;
      }

      .step-label {
        color: #409eff;
      }
    }
  }

  .step-circle {
    width: 40px;
    height: 40px;
    border: 2px solid #c0c4cc;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: white;
    margin-bottom: 8px;
    transition: all 0.3s;

    .step-number {
      font-size: 16px;
      font-weight: 600;
      color: #c0c4cc;
    }

    .step-check {
      display: flex;
      align-items: center;
      justify-content: center;

      .el-icon {
        font-size: 18px;
      }
    }
  }

  .step-label {
    font-size: 14px;
    color: #c0c4cc;
    font-weight: 500;
    transition: all 0.3s;
    white-space: nowrap;
  }
}

.step-content {
  min-height: 500px;
}

@media (max-width: 768px) {
  .self-service-registration {
    padding: 10px;
  }

  .step-progress {
    margin-bottom: 20px;

    .step-container {
      flex-wrap: wrap;
      justify-content: center;
      gap: 20px;

      &::before {
        display: none;
      }
    }

    .step-item {
      flex: 0 0 auto;
    }

    .step-label {
      font-size: 12px;
    }
  }
}
</style>